package net.wantongtech.xa.uploadbasicinfo.service;

import cn.com.taiji.sdk.tools.JsonTools;
import com.google.common.collect.Lists;
import com.wtkj.constant.NewClearingConstant;
import com.wtkj.exception.BusinessException;
import com.wtkj.vo.dzzf.base.xxdl.InteractionOrgMsgReceive;
import com.wtkj.zwxt.clearing.vo.clear.detail.EtcClearDetail;
import com.wtkj.zwxt.clearing.vo.clear.item.EtcClearItem;
import com.wtkj.zwxt.clearing.vo.clear.model.EtcClearModel;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.config.SCPClientConfig;
import net.wantongtech.xa.uploadbasicinfo.dao.CorrectErrorClearingFileTypeDao;
import org.apache.commons.io.FileUtils;
import org.csource.client.FastDFSClient;
import org.csource.common.MyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

import static com.wtkj.constant.NewClearingConstant.TransType.EXPAND_TRANS;

/**
 * 纠正错误的清分数据类型服务实现
 *
 * @author MaShibo
 * 日期 :  2020/2/5
 */
@Slf4j
@Service
public class CorrectErrorClearingFileTypeService {


    @Resource
    private CorrectErrorClearingFileTypeDao correctErrorClearingFileTypeDao;

    @Resource
    private SCPClientConfig scpClientConfig;

    public void correct() {
//        List<String> receiveIdList = correctErrorClearingFileTypeDao.queryCorrectingErrorReceiveId();
        List<String> receiveIdList = Lists.newArrayList(
                "17878B79-254D-2FC0-A14A-74C6F3E18277",
                "B5D8D432-6F9F-B22C-6E1B-BB6342D3D491",
                "DFB5192A-2EF3-ED30-3C2E-5A96EB7A8613",
                "5AC1B366-5327-FD50-8BE1-C38AF9171A4E",
                "C33B9DEE-5EE8-CC83-3D07-A14BD5780B59",
                "8F9A6B18-4E5F-1E63-E4DA-0CF350BBF024"
        );
        log.info("共{}条接收表数据待处理", receiveIdList.size());
        if (receiveIdList.isEmpty()) {
            return;
        }
        receiveIdList.forEach(receiveId -> {
            try {
                correctSingle(receiveId);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    private void correctSingle(String receiveId) throws MyException, IOException {
        InteractionOrgMsgReceive ormObj = new InteractionOrgMsgReceive();
        ormObj.setListID(receiveId);
        InteractionOrgMsgReceive receiveMsg = (InteractionOrgMsgReceive) correctErrorClearingFileTypeDao.queryObject(ormObj);
        if (receiveMsg == null) {
            log.warn("ListId为：{}的接收表数据不存在", receiveId);
            return;
        }
        String storePath = receiveMsg.getStorePath();
        log.info("ListId：{}，对应文件存储路径：{}", receiveId, storePath);

        Integer storeFlag = receiveMsg.getStoreFlag();

        //文件名
        String fileName = storePath.substring(storePath.lastIndexOf(File.separator) + 1);
        String json;
        if (storeFlag == 1) {
            json = FastDFSClient.downLoadFile(storePath, null);
        } else {
            json = FileUtils.readFileToString(new File(storePath), "UTF-8");
        }

        EtcClearModel model = JsonTools.json2Object(json, EtcClearModel.class);


        //纠正错误的fileType值
        List<EtcClearDetail> clearDetailList = model.getClearDetail();
        clearDetailList.forEach(clearDetail -> {
            List<EtcClearItem> clearItemList = clearDetail.getClearItems();

            clearItemList.forEach(clearItem -> correctClearItem(clearDetail, clearItem));
        });


        //生成并保存新json文件
        String newJson = JsonTools.toJsonStr(model);
        File dir = Paths.get(scpClientConfig.getLocalStorePath(), "clear").toFile();
        if (!dir.exists() && !dir.mkdirs()) {
            throw new BusinessException(String.format("文件路径：%s，创建失败", dir));
        }
        File newFile = new File(dir, fileName);
        FileUtils.writeStringToFile(newFile, newJson, "UTF-8");
        String newFilePath = newFile.getAbsolutePath();
        log.info("修正FileType后文件：{}，保存成功", newFilePath);


        //更新文件存储路径
        ormObj.setStoreFlag(InteractionOrgMsgReceive.STORE_FLAG_DISK);
        ormObj.setStorePath(newFile.getAbsolutePath());
        correctErrorClearingFileTypeDao.updateObject(ormObj);

    }

    private void correctClearItem(EtcClearDetail clearDetail, EtcClearItem clearItem) {
        String tollProvinceId = clearDetail.getTollProvinceId();
        String issuerId = clearDetail.getIssuerId();
        Long fileId = clearItem.getFileId();
        Integer fileType = clearItem.getFileType();

        Integer disputedCount = clearDetail.getDisputedCount();

        boolean hasDisputedTrans = disputedCount > 0;

        if (fileType == NewClearingConstant.FileType.DISPUTE.getValue() && hasDisputedTrans) {
            log.info("fileType：{}，非待处理类型，跳过处理", fileType);
            return;
        }

        Integer targetType = correctErrorClearingFileTypeDao.queryTargetTransType(tollProvinceId, issuerId, fileId);

        if (targetType == null) {
            log.info("未获取到tollProvinceId：{}，issuerId：{}，messageId：{}对应的原始交易类型", tollProvinceId, issuerId, fileId);
            return;
        }


        int realFileType;
        if (targetType == EXPAND_TRANS.getValue()) {
            realFileType = NewClearingConstant.FileType.EXPAND.getValue();
        } else {
            realFileType = targetType + 1;
        }

        if (realFileType != fileType) {
            log.info("fileType：{}与实际fileType：{}不一致，进行修改", fileType, realFileType);
            clearItem.setFileType(realFileType);
        }

    }
}
